﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.Sql;
using System.Data.Entity.Infrastructure;
using System.Data.Entity;
using System.IO;
using System.Data.Entity.Core.Objects;

namespace BYS.XiAnComDept.BussLogic
{
    public class ComDeptContext : DbContext
    {
        public static string dbPath = Path.Combine(Environment.CurrentDirectory, "DB") + @"\ComDept.mdf";

        public ComDeptContext()
            : base(@"Data Source=(LocalDB)\v11.0;AttachDbFilename=" + dbPath + @";Integrated Security=True;Connect Timeout=30")
        {
            Database.SetInitializer<ComDeptContext>(null);
        }

        public ObjectContext ObjContext { get { return ((IObjectContextAdapter)this).ObjectContext; } } 

        public DbSet<Company> Companies { get; set; }

        public DbSet<Fund> Funds { get; set; }

        public DbSet<FundType> FundTypes { get; set; }

        public DbSet<ProjectField> ProjectFields { get; set; }

        public DbSet<AppSetting> AppSettings { get; set; }

        public string BackupDb()
        {
            string dbBackup = Path.Combine(Environment.CurrentDirectory, "DB", 
                string.Format("ComDept{0}.bak", DateTime.Now.ToString("yyyyMMddHHmmss")));
            if (File.Exists(dbBackup))
            {
                File.Delete(dbBackup);
            }
            var cmd = String.Format("declare @dbName as varchar(100) = DB_NAME();BACKUP DATABASE {0} TO DISK='{1}' WITH FORMAT, MEDIANAME='DbBackups', MEDIADESCRIPTION='Media set for {0} database';"
                               , "@dbName", dbBackup);
            this.Database.ExecuteSqlCommand(TransactionalBehavior.DoNotEnsureTransaction, cmd);

            return dbBackup;
        }

        public void RestoreDb(string backupFile)
        {
            var cmd = String.Format("USE [Master];  " +
                     "ALTER DATABASE [{0}] SET SINGLE_USER WITH ROLLBACK IMMEDIATE;" +
                     "RESTORE DATABASE [{0}] " +
                     "FROM DISK='{1}'  WITH REPLACE; " +
                     "ALTER DATABASE [{0}]  SET MULTI_USER;",
                     dbPath,
                     backupFile);
            this.Database.ExecuteSqlCommand(TransactionalBehavior.DoNotEnsureTransaction, cmd);
        }

        public string[] GetAllBackupFiles()
        {
             return Directory.GetFiles(Path.Combine(Environment.CurrentDirectory, "DB"), "*.bak");
        }

        public void ComDeptContext_SmokeTest()
        {
            using (ComDeptContext context = new ComDeptContext())
            {
                Fund fund = new Fund()
                {
                    Company = new Company() { CompanyName = "TestCom", CompanyPreName = "TestCom1, TestCom2" },
                    Amount = 12.2M,
                    Comment = "Test",
                    DueAmount = 10,
                    FundStatus = "通过",
                    FundType = new FundType() { FundTypeName = "TestType" },
                    ProjectFields = new System.Collections.ObjectModel.ObservableCollection<ProjectField>(new ProjectField[]{
                        new ProjectField(){FieldName = "出口资金", FieldValue = "12"},
                        new ProjectField(){FieldName = "进口金额", FieldValue = "52"}
                    }),
                    Year = DateTime.Now
                };

                context.Funds.Add(fund);
                context.SaveChanges();
            }
        }

        public void ComDeptContext_BackupDbTest()
        {
            string backupFile = null;
            using (ComDeptContext db = new ComDeptContext())
            {
                string[] allBackupFiles = GetAllBackupFiles();
                backupFile = db.BackupDb();
                db.RestoreDb(backupFile);
            }
        }
    }
}
